//
//  HPCustomerViewController.m
//  HappyPenguin
//
//  Created by zhuangyihang on 1/9/16.
//  Copyright © 2016 zhuangyihang. All rights reserved.
//

#import "HPCustomerViewController.h"

#import "HPCustomerInfoAddViewController.h"

#import "HPCustomerInfoView.h"
#import "KSViewPagerView.h"

#import "HPCustomerInfoDataSource.h"
#import "HPCustomerHistoryDataSource.h"
#import "HPCustomerSnapshotDataSource.h"
#import "HPCustomerWardrobeDataSource.h"

#import "HPCustomerSmsViewController.h"

#import "HPHttpVipInfoRequest.h"
#import "HPHttpVipSnapshotRequest.h"
#import "HPHttpVipWardrobeRequest.h"

static const CGFloat kInfoPanelHeightRatio = 0.65;
static const NSInteger kCollectionColumn = 2;
static const NSInteger kCollectionCellMargin = 10;

static const NSInteger kInfoButtonHeight = 40;

@interface HPCustomerViewController ()<UIScrollViewDelegate>

@property (nonatomic, strong) HPCustomerInfoView *infoPanel;
@property (nonatomic, strong) KSViewPagerView *pagerView;
@property (nonatomic, strong) UIScrollView *mainScrollView;


@property (nonatomic, strong) HPCustomerInfoDataSource *infoDataSource;
@property (nonatomic, strong) HPCustomerHistoryDataSource *historyDataSource;
@property (nonatomic, strong) HPCustomerSnapshotDataSource *snapshotDataSource;
@property (nonatomic, strong) HPCustomerWardrobeDataSource *wardrobeDataSource;


@property (nonatomic, strong) HPHttpVipInfoRequest *infoReqeust;
@property (nonatomic, strong) HPHttpVipWardrobeRequest *wardrobeReqeust;
@property (nonatomic, strong) HPHttpVipSnapshotRequest *snapshotRequest;


@property (nonatomic, strong) NSArray *segmentArray;
@end

@implementation HPCustomerViewController

- (id)init{
    self = [super init];
    if (self) {
        self.segmentArray = @[@"资料",@"足迹",@"衣柜",@"快照"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self addBackButton:nil];
    [self setBaseNavigationBarBackgroundColor:[UIColor clearColor]];
    [self setupFullContentView];
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Private
- (void)setupUI{
    [self setupBarButton];
    [self setupCustomerInfoPanel];
    [self setupSegment];
    [self setupContentScroll];
}

- (void)setupBarButton{
    [self addRightButtonSelector:@selector(add)];
    [self setRightButtonImage:[UIImage imageNamed:@"Button_Add"]];
    
    UIButton *photo = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.baseNavigationBarView addSubview:photo];
    [photo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.right.equalTo(self.baseRightButton.mas_left);
        make.centerY.equalTo(self.baseRightButton);
    }];
    [photo setImage:[UIImage imageNamed:@"Button_Photo"] forState:UIControlStateNormal];
    
}

- (void)setupSegment{
    WS(ws);
    
    self.pagerView = [[KSViewPagerView alloc] initWithArray:self.segmentArray];
    [self.baseContentView addSubview:self.pagerView];
    self.pagerView.backgroundColor = [UIColor whiteColor];
    [self.pagerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.equalTo(self.baseContentView);
        make.height.equalTo(@40);
        make.top.equalTo(self.infoPanel.mas_bottom);
    }];
    
    [self.pagerView setActiveColor:[UIColor colorWithRGB:0x4fbcff]];
    [self.pagerView setInactiveColor:[UIColor colorWithRGB:0xafafaf]];
    [self.pagerView setTitleFont:[UIConstants getFont:15]];
    self.pagerView.click = ^(KSViewPagerView*v, NSNumber *index){
        [ws.mainScrollView setContentOffset:CGPointMake([index intValue]*v.width, 0) animated:YES];
    };
    
    [self.pagerView setCursorPosition:0];
    
    UIView *sep = [UIView new];
    [self.baseContentView addSubview:sep];
    [sep mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.baseContentView);
        make.centerX.equalTo(self.baseContentView);
        make.top.equalTo(self.pagerView.mas_bottom);
        make.height.equalTo(@1);
    }];
    sep.backgroundColor = [UIColor colorWithRGB:0xefefef];

}

- (void)setupContentScroll{
    self.mainScrollView = [UIScrollView new];
    [self.baseContentView addSubview:self.mainScrollView];
    [self.mainScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.pagerView.mas_bottom).offset(1);
        make.width.centerX.equalTo(self.pagerView);
        make.bottom.equalTo(self.baseContentView);
    }];
    self.mainScrollView.pagingEnabled = YES;
    self.mainScrollView.delegate = self;
    self.mainScrollView.contentSize = CGSizeMake([UIScreen mainScreen].bounds.size.width * self.segmentArray.count, 0);
    
    [self addInfoPanel];
    [self addHistoryPanel];
    [self addWardrobePanel];
    [self addSnapshotPanel];
}

- (void)setupCustomerInfoPanel{
    HPCustomerInfoView *panel = [HPCustomerInfoView new];
    [self.baseContentView addSubview:panel];
    [panel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.width.centerX.equalTo(self.baseContentView);
        make.height.equalTo(panel.mas_width).multipliedBy(kInfoPanelHeightRatio);
    }];
    self.infoPanel = panel;
}

- (void)refreshInfoPanel{
    self.infoPanel.portrait = [self.infoDataSource.infoObject vipPortrait];
    self.infoPanel.fee = [[self.infoDataSource.infoObject vipTotalMoney] integerValue];;
    self.infoPanel.purchaseTimes = [[self.infoDataSource.infoObject vipTotalCount] integerValue];
    self.infoPanel.noPurchaseDays = [[self.infoDataSource.infoObject vipLastBuy] integerValue];
    self.infoPanel.name = [self.infoDataSource.infoObject vipName];
    self.infoPanel.gender = [self.infoDataSource.infoObject vipGender];
}

- (void)addInfoPanel{
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [self.mainScrollView addSubview:tableView];
    self.mainScrollView.alwaysBounceVertical = NO;
    tableView.tableFooterView = [UIView new];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainScrollView);
        make.width.equalTo(self.mainScrollView);
        make.height.equalTo(self.mainScrollView).offset(-kInfoButtonHeight);
        make.top.equalTo(self.mainScrollView);
    }];
    
    self.infoDataSource = [[HPCustomerInfoDataSource alloc] initWithTableView:tableView];
    
    NSArray *a = @[@"打电话",@"发短信",@"发微信"];
    for (int i = 0; i < 3; i++) {
        UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.mainScrollView addSubview:b];
        [b mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.mainScrollView).multipliedBy(1.0/a.count);
            make.height.mas_equalTo(kInfoButtonHeight);
            if (i==0) {
                make.left.equalTo(self.mainScrollView);
            }else if(i==1){
                make.centerX.equalTo(tableView);
            }else if(i==2){
                make.right.equalTo(tableView);
            }
            
            make.top.equalTo(tableView.mas_bottom);
        }];
        [b setTitle:a[i] forState:UIControlStateNormal];
        [b setTitleColor:[UIColor colorWithRGB:0x74cefe] forState:UIControlStateNormal];
        [b setBackgroundImage:[UIImage imageNamed:@"Button_CustomerNormal"] forState:UIControlStateNormal];
        [b setBackgroundImage:[UIImage imageNamed:@"Button_CustomerHL"] forState:UIControlStateHighlighted];
        [b setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        b.tag = i;
        
        
        WS(ws);
        [b bk_addEventHandler:^(UIButton *sender) {
            switch (sender.tag) {
                case 0:
                {
                    [ws call];
                }
                    break;
                case 1:
                {
                    [ws sms];
                }
                    break;
                case 2:
                {
                    [ws wechat];
                }
                    break;
                default:
                    break;
            }
        } forControlEvents:UIControlEventTouchUpInside];
    }
    
    WS(ws);
    self.infoReqeust = [[HPHttpVipInfoRequest alloc] init];
    self.infoReqeust.vipId = self.vipId;
    self.infoReqeust.responseBlock = ^(HPHttpVipInfoResponse *response, HttpError *error){
        if (error) {
            
        }else{
            ws.infoDataSource.infoObject = response.info;
            [ws refreshInfoPanel];
            [tableView reloadData];
        }
    };
    [self.infoReqeust send];
}

- (void)addHistoryPanel{
    UITableView *tableView = [UITableView new];
    [self.mainScrollView addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainScrollView).offset([UIScreen mainScreen].bounds.size.width);
        make.size.equalTo(self.mainScrollView);
        make.top.equalTo(self.mainScrollView);
    }];
    self.historyDataSource = [[HPCustomerHistoryDataSource alloc] initWithTableView:tableView];
}

- (void)addWardrobePanel{
    float width = floor((self.view.width-(kCollectionColumn+1)*kCollectionCellMargin)/kCollectionColumn);
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake( width, width*1.3 );
    layout.minimumInteritemSpacing = kCollectionCellMargin;

    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    [self.mainScrollView addSubview:collection];
    [collection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mainScrollView).offset([UIScreen mainScreen].bounds.size.width*2);
        make.height.equalTo(self.mainScrollView);
        make.width.equalTo(self.mainScrollView).offset(-2*kCollectionCellMargin);
        make.top.equalTo(self.mainScrollView);
    }];
    collection.backgroundColor = [UIColor clearColor];
    
    self.wardrobeDataSource = [[HPCustomerWardrobeDataSource alloc] initWithTableView:collection];
    
    
    WS(ws);
    self.wardrobeReqeust = [[HPHttpVipWardrobeRequest alloc] init];
    self.wardrobeReqeust.vipId = self.vipId;
    self.wardrobeReqeust.responseBlock = ^(HPHttpVipWardrobeResponse *response, HttpError *error){
        if (error) {
            
        }else{
            ws.wardrobeDataSource.datas = response.results;
            [collection reloadData];
        }
    };
    [self.wardrobeReqeust pullRefresh];
}

- (void)addSnapshotPanel{
    UITableView *tableView = [UITableView new];
    [self.mainScrollView addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mainScrollView).offset([UIScreen mainScreen].bounds.size.width*3);
        make.size.equalTo(self.mainScrollView);
        make.top.equalTo(self.mainScrollView);
    }];
    tableView.tableFooterView = [UIView new];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = [UIColor colorWithRGB:0xf1f1f1];
    self.snapshotDataSource = [[HPCustomerSnapshotDataSource alloc] initWithTableView:tableView];
    
    self.snapshotRequest = [[HPHttpVipSnapshotRequest alloc] init];
    self.snapshotRequest.vipId = self.vipId;
    self.snapshotRequest.responseBlock = ^(HPHttpVipWardrobeResponse *response, HttpError *error){
        if (error) {
            
        }else{
        }
    };
    [self.snapshotRequest send];
}

#pragma mark - Click
- (void)add{
    HPCustomerInfoAddViewController *v = [[HPCustomerInfoAddViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:v];
    [nav setNavigationBarHidden:YES];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

- (void)call{
    NSString *title = [NSString stringWithFormat:@"是否拨打%@",[self.infoDataSource.infoObject vipPhone]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"拨打" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSString *url = [NSString stringWithFormat:@"tel://%@",[self.infoDataSource.infoObject vipPhone]];
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
    }];
    UIAlertAction *secondAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    }];
    [alert addAction:secondAction];
    [alert addAction:firstAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)sms{
    HPCustomerSmsViewController *v = [[HPCustomerSmsViewController alloc] init];
    v.vip = self.infoDataSource.infoObject;
    [self.navigationController pushViewController:v animated:YES];
}

- (void)wechat{
    
}

#pragma mark - UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float page = scrollView.contentOffset.x/scrollView.width;
    [self.pagerView setCursorPosition:page];
}
@end
